﻿// SMIL is a community project available under the Microsoft Public License (Ms-PL)
// Code is provided as is and with no warrenty – Use at your own risk
// View the project and the latest code at http://smil.codeplex.com/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Browser;
using System.Xml.Linq;
using Microsoft.Maps.MapControl;

namespace SMIL.InfoTool
{    
    public partial class InfoTool : UserControl, IDisposable
    {        
        SPCommunication.ASMX.SPGeoRssSISoapClient client;
        
        InfoToolParams _i;

        const int _HeaderLength = 10;

        public InfoTool(InfoToolParams i)
        {
            InitializeComponent();

            _i = i;            
            client = SPCommunication.Proxy.GetProxy;
            client.GetSPItemDetailCompleted += client_GetSPItemDetailCompleted;
            Loaded += new RoutedEventHandler(InfoTool_Loaded);
            MouseLeave += new MouseEventHandler(InfoTool_MouseLeave);
        }

        #region inner class ItemDetail
        public class ItemDetail
        {
            public ItemDetail()
            { }
            public ItemDetail(string fieldName, string fieldType, string fieldValue)
            {
                this.fieldName = fieldName;
                this.fieldType = fieldType;
                this.fieldValue = fieldValue;
            }

            public string fieldName { get; set; }
            public string fieldType { get; set; }
            public string fieldValue { get; set; }

            public LinkedItem LinkedItems { get; set; }
        }

        public sealed class LinkedItem
        {
            public string Title { get; set; }
            public List<LinkedItemDetail> Items { get; set; }
        }

        public sealed class LinkedItemDetail
        {
            public string Title { get; set; }
            public string Url { get; set; }
        }
        #endregion


        public XElement Details
        {
            set
            {
                theTabControl.Items.Clear();
                IEnumerable<XElement> elements = from detail in value.Elements("detail") select detail;
                List<ItemDetail> mainTableList = new List<ItemDetail>();

                foreach (XElement detail in elements)
                {

                    if (detail.HasElements)
                    {
                        IEnumerable<XElement> childElements = from childDetail in detail.Elements("detail") select childDetail;
                        List<ItemDetail> childTableList = new List<ItemDetail>();
                        foreach (XElement childDetail in childElements)
                        {
                            ItemDetail childItemDetail = new ItemDetail();

                            childItemDetail.fieldName = childDetail.Attribute("title").Value.ToString();
                            childItemDetail.fieldType = childDetail.Attribute("url").Value.ToString();
                            childItemDetail.fieldValue = childDetail.Value.ToString();
                            childTableList.Add(childItemDetail);
                        }
                        ListBox listBox = new ListBox();
                        listBox.ItemsSource = childTableList;
                        listBox.ItemTemplate = (DataTemplate)this.Resources["linkedItemdetail"];
                        listBox.Style = (Style)this.Resources["ListBoxStyle"];
                        Grid childGrid = new Grid();
                        childGrid.Children.Add(listBox);

                        TabItem childTabItem = new TabItem();
                        childTabItem.Header = detail.Attribute("fieldName").Value.ToString();
                        childTabItem.Content = childGrid;
                        theTabControl.Items.Add(childTabItem);
                    }
                    else
                    {
                        ItemDetail itemDetail = new ItemDetail();

                        itemDetail.fieldName = detail.Attribute("fieldName").Value.ToString();
                        itemDetail.fieldType = detail.Attribute("type").Value.ToString();
                        itemDetail.fieldValue = detail.Value.ToString();
                        mainTableList.Add(itemDetail);
                    }

                }

                ListBox lb = new ListBox();
                lb.ItemsSource = mainTableList;
                lb.ItemTemplate = (DataTemplate)this.Resources["itemdetail"];
                lb.Style = (Style)this.Resources["ListBoxStyle"];
                Grid grid = new Grid();
                grid.Children.Add(lb);

                TabItem mainTabItem = new TabItem();
                mainTabItem.Header = _i.Subtitle;
                mainTabItem.Content = grid;

                theTabControl.Items.Insert(0,mainTabItem);
                theTabControl.SelectedIndex = 0;
                

                try
                {
                    ItemDetail id = mainTableList.First(param => param.fieldName == "ID");
                    _i.SPItemID = id.fieldValue;
                }
                catch
                {
                }
            }
        }

        void InfoTool_Loaded(object sender, RoutedEventArgs e)
        {
            PART_Title.Text = _i.Title;
            PART_Subtitle.Text = _i.Subtitle;
        }

        private void PART_Views_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            GetDetails();
        }               

        public void GetDetails()
        {            
            client.GetSPItemDetailAsync(new SMIL.SPCommunication.ASMX.ItemDetailRequest()
            {
                SiteUrl = _i.SPSiteURI,
                SPItemGuid = _i.Guid,
                SPListname = _i.ListName,
                SPViewName = _i.ViewName
            });
        }

        void client_GetSPItemDetailCompleted(object sender, SMIL.SPCommunication.ASMX.GetSPItemDetailCompletedEventArgs e)
        {
            if (e.Error != null)
                throw e.Error;

            Details = e.Result.SPItemDetail;
        }

        private void PART_Openbutton_Click(object sender, RoutedEventArgs e)        
        {
            HtmlPage.Window.Navigate(new Uri(_i.ObjectUrl), "_blank");
        }

        private void PART_Selectbutton_Click(object sender, RoutedEventArgs e)        
        {
            try
            {
                HtmlPage.Window.Invoke("ConnectScript", new string[] { _i.SPItemID });
            }
            catch (Exception ex)
            {
                string msg = string.Empty;
                msg = ex.Message;
                while (ex.InnerException != null)
                {
                    msg += "... Innerexception: " + ex.Message;
                    ex = ex.InnerException;
                }

                MessageBox.Show("Någonting fel vid anrop till Web Part Javascript. Meddelande: " + msg);
            }
        }

        #region IDisposable Members

        public void Dispose()
        {
            MouseLeave -= InfoTool_MouseLeave;
        }

        #endregion

        void InfoTool_MouseLeave(object sender, MouseEventArgs e)
        {
            //Close();
        }            

        private void PART_CloseButton_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }   
     
        private void Close()
        {
            //_i.Layer.Children.Clear();
            ((MapLayer)((ContentControl)this.Parent).Parent).Children.Remove(this);
            this.Dispose();
        }

        private string GetClippedString(string str, int length)
        {
            return str.Substring(0, (str.Length > length ? length : str.Length));
        }

        private void bLinkedItemDetail_Click(object sender, RoutedEventArgs e)
        {
            if (sender == null)
                return;

            Button b = (Button)sender;
            var url = b.Tag as string;
            if (!string.IsNullOrEmpty(url))
                HtmlPage.Window.Navigate(new Uri(url), "_blank");
        }
    }
}
